package org.spring.boot.multiple.mybatis.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * @author: eastcom
 * @desc: 多数据源配置
 **/
@Configuration("fmDataSourceConfig")
@MapperScan(basePackages = {FmDataSourceConfig.FM_BASE_PACKAGES},
		sqlSessionFactoryRef = "fmSqlSessionFactory")
public class FmDataSourceConfig {

	static final String FM_MAPPER_LOCATIONS = "classpath:org/spring/boot/multiple/mybatis/mapper/fm/*.xml";

	static final String FM_BASE_PACKAGES = "org.spring.boot.multiple.mybatis.dao.fm";

	@Bean("fmDataSource")
	@Qualifier("fmDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.fm")
	@Primary
	public DataSource getFmDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "fmTransactionManager")
	@Primary
	public DataSourceTransactionManager getFmDataSourceTransactionManager() {
		return new DataSourceTransactionManager(this.getFmDataSource());
	}

	@Bean(name = "fmSqlSessionFactory")
	@Primary
	public SqlSessionFactory getFmSqlSessionFactory(@Qualifier("fmDataSource") DataSource dataSource) throws Exception {
		final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
		sessionFactory.setDataSource(dataSource);
		sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(FmDataSourceConfig.FM_MAPPER_LOCATIONS));
		return sessionFactory.getObject();
	}
}